package com.neutech.handler;

import com.neutech.enumeration.CategoryStatus;
import com.neutech.enumeration.ProductStatusEnum;
import com.neutech.enumeration.StatusBehaviour;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.INTEGER)
@MappedTypes({ProductStatusEnum.class, CategoryStatus.class})
public class StatusHandler extends BaseTypeHandler<StatusBehaviour>{
    private final Class<StatusBehaviour> type;
    private final StatusBehaviour[] enums;

    public StatusHandler(Class<StatusBehaviour> type) {
        if (type == null)
            throw new IllegalArgumentException("Type argument cannot be null");
        this.type = type;
        this.enums = type.getEnumConstants();
        if (this.enums == null)
            throw new IllegalArgumentException(type.getSimpleName()
                    + " does not represent an enum type.");
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, StatusBehaviour parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setInt(i, parameter.getStatusCode());
    }

    @Override
    public StatusBehaviour getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int i = rs.getInt(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            return locateEnumBehaviour(i);
        }
    }

    @Override
    public StatusBehaviour getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int i = rs.getInt(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            return locateEnumBehaviour(i);
        }
    }

    @Override
    public StatusBehaviour getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int i = cs.getInt(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            return locateEnumBehaviour(i);
        }
    }


    private StatusBehaviour locateEnumBehaviour(int code) {
        for (StatusBehaviour status : enums) {
            if (status.getStatusCode() == code) {
                return status;
            }
        }
        throw new IllegalArgumentException("Unknown Enum Type：" + code + "," + type.getSimpleName());
    }
}
